//
//  CXAlertCXCenterView.swift
//  CXSwiftDemo
//
//  Created by 潮汐 on 2023/12/7.
//

import UIKit

extension CXAlertCXCenterView {
    /// 【自己封装的】aleat-Swift
    /// - Parameters:
    ///   - controller: 弹窗所在控制器
    ///   - title: 标题
    ///   - message: 内容
    ///   - array: 按钮
    ///   - type: 类型，-1代表默认，0代表成功；40代表内容文字左对齐
    ///   - handler: 回调
    static func AlertCXCenterAlertWithController(Controller controller: UIViewController?, Title title: String, Message message: String, otherItemArrays array:[String], Type type: Int, handler: @escaping (_ indexCenter: Int) -> Void) {
        if array.count > 2 {
            print("按钮个数必最多只能是2个")
            return;
        }
        if (title.count <= 0 && message.count <= 0 ) {
            //都为空
            return;
        }
        let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
        
        let viewWX = window?.viewWithTag(131450623)
        //控件不存在才创建，防止重复创建
        if viewWX==nil {
            let alertView = CXAlertCXCenterView()
            alertView.tag = 131450623
            window?.addSubview(alertView)
            alertView.widthAlter = 280
            alertView.type = type
            alertView.titleText = title
            alertView.subTitleText = message
            alertView.array = array
            alertView.controller = controller 
            //创建UI
            alertView.setUpContentViewAray(array: array)
            //block回调
            alertView.actionBlockAtIndex = { index in
                handler(index)//回调
            }
        }
    }
    
    
    
    /// 【系统的】aleat-Swift
    /// - Parameters:
    ///   - controller: 弹窗所在控制器
    ///   - title: 标题
    ///   - message: 内容
    ///   - array: 按钮
    ///   - type: 类型，-1代表默认，0代表成功；40代表内容文字左对齐
    ///   - handler: 回调
    static func AlertSystemCXCenterAlertWithTitle(Controller controller: UIViewController?, Title title: String, Message message: String, otherItemArrays array:[String], Type type: Int, handler: @escaping (_ indexCenter: Int) -> Void){
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        if type == 40 {
            //设置内容左对齐
//            let label1 = alertController.view.value(forKeyPath: "_titleLabel")
            let labelMessage = alertController.view.value(forKeyPath: "_messageLabel") as? UILabel
            labelMessage?.textAlignment = .left
        }
        
        if array.count == 1 {
            //只有一个按钮
            //确定
            let okAction = UIAlertAction(title: array.first, style: .default) { action in
                handler(0)
            }
            alertController.addAction(okAction)
        }else if array.count == 2 {
            //2个按钮
            //
            let actionOne = UIAlertAction(title: array.first, style: .default) { action in
                handler(0)
            }
            alertController.addAction(actionOne)
            //
            let actionTwo = UIAlertAction(title: array.last, style: .default) { action in
                handler(1)
            }
            alertController.addAction(actionTwo)
            
            //kvc修改取消按钮颜色，找到那个按钮是取消
            if actionOne.title == "取消" {
                actionOne.setValue(UIColor.gray, forKey: "titleTextColor")
            }
            if actionTwo.title == "取消" {
                actionOne.setValue(UIColor.gray, forKey: "titleTextColor")
            }
        }
// UIApplication.shared.keyWindow?.rootViewController:
// 'keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes
        let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
        window?.rootViewController?.present(alertController, animated: true, completion: nil)
    }
}


class CXAlertCXCenterView: UIView {
    //声明一个闭包（多返回值），必须用？号
    var actionBlockAtIndex:((_ index: Int)->())?
    //弹框宽度
    var widthAlter: Double = 0
    //类型
    var type: Int = -1
    //标题
    var titleText: String = ""
    //内容
    var subTitleText: String = ""
    //
    var array = [String]()
    //
    var controller: UIViewController? = nil
    //内容视图
    lazy var contentView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        //设置蒙版层背景色
        self.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.65)
        //开启用户交互
        self.isUserInteractionEnabled = true
        //添加点击手势（拦截点击事件）
        let tap = UITapGestureRecognizer(target: self, action: #selector(ActionView))
        self.addGestureRecognizer(tap)
        //关键盘
        let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
        window?.endEditing(true)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //创建UI
    func setUpContentViewAray(array:[String]) {
        DispatchQueue.main.async {
            self.contentView.backgroundColor = .white
            self.contentView.layer.cornerRadius = 10
            self.contentView.clipsToBounds = true
            //拦截点击事件
            self.contentView.isUserInteractionEnabled = true
            self.addSubview(self.contentView)//添加控件
            //添加点击手势（拦截点击事件）
            let tap = UITapGestureRecognizer(target: self, action: #selector(self.ActionView))
            self.contentView.addGestureRecognizer(tap)
            //创建UI
            self.createUITwo(array: array)
        }
    }
    
//MARK: ========== UI ===============
    func createUITwo(array:[String]){
        //添加大标题
        let titleHeight = String.textAutoHeight(text: self.titleText, width: self.widthAlter-40, font: .boldSystemFont(ofSize: 20))
        let titleLabel = UILabel()
        titleLabel.text = self.titleText
        titleLabel.font = .boldSystemFont(ofSize: 20)
        titleLabel.textColor = .black
        titleLabel.numberOfLines = 1
        titleLabel.textAlignment = .center
        self.contentView.addSubview(titleLabel)
        
        //副标题
        let subtitleHeight = String.textAutoHeight(text: self.subTitleText, width: self.widthAlter-40, font: .systemFont(ofSize: 16))
        let messageLabel = UILabel()
        messageLabel.text = self.subTitleText
        messageLabel.font = .systemFont(ofSize: 16)
        messageLabel.textColor = HexRGB(0x5A5A5A)
        messageLabel.numberOfLines = 0
        self.contentView.addSubview(messageLabel)
        if self.type == 40 {
            //内容左对齐
            messageLabel.textAlignment = .left
        }else{
            messageLabel.textAlignment = .center
        }
//MARK: ========== 判断类型 =================
        var contentY = 0.0
        if self.titleText.count > 0 && self.subTitleText.count <= 0 {
            //只有大标题，没有副标题
            titleLabel.frame = CGRect(x: 20, y: 20, width: self.widthAlter-40, height: titleHeight)
            messageLabel.isHidden = true
            contentY = titleLabel.bottom
        }else if self.titleText.count <= 0 && self.subTitleText.count >= 0 {
            //只有副标题，没有大标题
            titleLabel.isHidden = true
            messageLabel.frame = CGRect(x: 20, y: 20, width: self.widthAlter-40, height: subtitleHeight)
            contentY = messageLabel.bottom
        }else{
            //大标题和副标题同时存在
            titleLabel.frame = CGRect(x: 20, y: 20, width: self.widthAlter-40, height: titleHeight)
            messageLabel.frame = CGRect(x: 20, y: titleLabel.bottom + 20, width: self.widthAlter-40, height: subtitleHeight)
            contentY = messageLabel.bottom
        }
        
        //按钮内容分割线
        let viewLineH = UIView()
        viewLineH.frame = CGRect(x: 0, y: contentY+20, width: self.widthAlter, height: 1)
        viewLineH.backgroundColor = HexRGB(0xD5D5D5)
        self.contentView.addSubview(viewLineH)
        
        if array.count == 1  {
            //只有一个按钮
            let buttonOne = UIButton(type: .custom)
            buttonOne.frame = CGRect(x: (self.widthAlter - self.widthAlter / 2) / 2, y: viewLineH.bottom, width: self.widthAlter/2, height: 50)
            buttonOne.setTitle(array.first, for: .normal)
            buttonOne.setTitleColor(.blue, for: .normal)
            buttonOne.titleLabel?.font = .systemFont(ofSize: 16)
            buttonOne.titleLabel?.adjustsFontSizeToFitWidth = true
            buttonOne.addTarget(self, action: #selector(btnActionOne), for: .touchUpInside)
            self.contentView.addSubview(buttonOne)
            //设置View坐标
            self.contentView.width = self.widthAlter
            self.contentView.height = buttonOne.bottom+15
            self.contentView.center = self.center
            
        }else{
            //2个按钮
            let buttonWidth = (self.widthAlter - 1) / 2;
            
            let buttonOne = UIButton(type: .custom)
            buttonOne.frame = CGRect(x: 0, y: viewLineH.bottom, width: buttonWidth, height: 50)
            buttonOne.setTitle(array.first, for: .normal)
            buttonOne.setTitleColor(HexRGB(0x5A5A5A), for: .normal)
            buttonOne.titleLabel?.font = .systemFont(ofSize: 16)
            buttonOne.titleLabel?.adjustsFontSizeToFitWidth = true
            buttonOne.addTarget(self, action: #selector(btnActionOne), for: .touchUpInside)
            self.contentView.addSubview(buttonOne)
            
            //两个按钮中间竖着的分割线
            let viewLineTwo = UIView()
            viewLineTwo.frame = CGRect(x: buttonOne.right, y: buttonOne.y, width: 1, height: 50)
            viewLineTwo.backgroundColor = HexRGB(0xD5D5D5)
            self.contentView.addSubview(viewLineTwo)
            
            //按钮2
            let buttonTwo = UIButton(type: .custom)
            buttonTwo.frame = CGRect(x: viewLineTwo.right, y: buttonOne.y, width: buttonWidth, height: 50)
            buttonTwo.setTitle(array.last, for: .normal)
            buttonTwo.setTitleColor(.blue, for: .normal)
            buttonTwo.titleLabel?.font = .systemFont(ofSize: 16)
            buttonTwo.titleLabel?.adjustsFontSizeToFitWidth = true
            buttonTwo.addTarget(self, action: #selector(btnActionTwo), for: .touchUpInside)
            self.contentView.addSubview(buttonTwo)
            
            //设置View坐标
            self.contentView.width = self.widthAlter
            self.contentView.height = buttonTwo.bottom
            self.contentView.center = self.center
        }
        
        //展示动画
        self.showAlertAnimation()
        
    }
    
    @objc func ActionView(){
        //什么也不干，拦截点击事件
    }
    
    @objc func btnActionOne(){
        //移除弹框
        self.ActionBackRemoView()
        //回调按钮点击标记
        if self.actionBlockAtIndex != nil {
            self.actionBlockAtIndex?(0)
        }
    }
    
    @objc func btnActionTwo(){
        //移除弹框
        self.ActionBackRemoView()
        //回调按钮点击标记
        if self.actionBlockAtIndex != nil {
            self.actionBlockAtIndex?(1)
        }
    }
    
    //点击移除view(动画少点，否则会造成两个弹窗弹不出来)默认0.2
    func ActionBackRemoView(){
        //控件动画影藏
        self.alpha = 0
        self.contentView.alpha = 0
        self.removeFromSuperview()
    }
    
    //展示动画
    func showAlertAnimation(){
        let animation = CAKeyframeAnimation(keyPath: "transform")
        animation.values = [NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1)),
                            NSValue(caTransform3D: CATransform3DMakeScale(1.05, 1.05, 1)),
                            NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1))
        ]
        animation.keyTimes = [NSNumber(value: 0), NSNumber(value: 0.5), NSNumber(value: 1)]
        animation.isRemovedOnCompletion = false
        animation.duration = 0.3
        self.contentView.layer.add(animation, forKey: "showAlert")
        
    }
    
    //移除动画
    func dismissAlertAnimation(){
        let animation = CAKeyframeAnimation(keyPath: "transform")
        animation.values = [NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1)),
                            NSValue(caTransform3D: CATransform3DMakeScale(0.95, 0.95, 1)),
                            NSValue(caTransform3D: CATransform3DMakeScale(0.8, 0.8, 1))
        ]
        animation.keyTimes = [NSNumber(value: 0), NSNumber(value: 0.5), NSNumber(value: 1)]
        animation.fillMode = .removed
        animation.duration = 0.01
        self.contentView.layer.add(animation, forKey: "dismissAlert")
    }
}
